package com.knowledgegraph.repository;

import com.knowledgegraph.entity.Resource;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

@Repository
public interface ResourceRepository extends JpaRepository<Resource, Long> {
    
    Optional<Resource> findByName(String name);
    
    List<Resource> findByResourceType(String resourceType);
    
    List<Resource> findByNameContainingIgnoreCase(String name);
    
    @Query("SELECT r FROM Resource r WHERE r.resourceType = :resourceType AND r.name LIKE %:name%")
    List<Resource> findByResourceTypeAndNameContaining(@Param("resourceType") String resourceType, @Param("name") String name);
    
    @Query("SELECT DISTINCT r.resourceType FROM Resource r")
    List<String> findAllResourceTypes();
    
    @Query("SELECT COUNT(r) FROM Resource r WHERE r.resourceType = :resourceType")
    Long countByResourceType(@Param("resourceType") String resourceType);
    
    @Query("SELECT r FROM Resource r WHERE r.id IN " +
           "(SELECT DISTINCT nr.resource.id FROM NodeResource nr WHERE nr.node.id = :nodeId)")
    List<Resource> findResourcesByNodeId(@Param("nodeId") Long nodeId);
    
    List<Resource> findByMimeType(String mimeType);
    
    @Query("SELECT r FROM Resource r WHERE r.filePath IS NOT NULL")
    List<Resource> findAllWithFilePath();
}